﻿using HelloMinasan.Web.Song.ViewModels;
using System.Linq;
using System.Web.Mvc;
using System;
using System.Web;
using System.IO;
using System.Globalization;
using HelloMinasan.Business;
using HelloMinasan.Domain;
using HelloMinasan.Framework.Web;
using HelloMinasan.Framework.Helpers;
using HelloMinasan.Resources;
using HelloMinasan.Framework.Web.WebHelpers;
using HelloMinasan.Business.Extend;


namespace HelloMinasan.Web.Song.Controllers
{
    public class UserManagementController : ApplicationController
    {
        //private readonly UserUnitWork _UserUnitWork = new UserUnitWork();
        //#region "Propertise"
        //private readonly IRepository._UserIRepository _IRepository;
        //public UserManagementController()
        //    : this(new UserIRepository())
        //{
        //}

        //private UserManagementController(IRepository._UserIRepository irepository)
        //{
        //    this._IRepository = irepository;
        //}
        //#endregion
        //

        private IUserService userService;
        private ISongService songService;

        public UserManagementController(ISongService songService, IUserService userService)
        {
            this.songService = songService;
            this.userService = userService;
        }

        // GET: /UserManagement/
        //[AllowAnonymous]
        public ActionResult MySong(int userId = 0)
        {
            if (userId == 0) //owner
            {
                var model = songService.GetSongsByUsername(CurrentUser.Id);
                ViewBag.User = CurrentUser.Id;//User.Identity.Name;
                return View(model);
            }
            else //songn of other users
            {
                var model = songService.GetSongsByUsername(userId);
                ViewBag.User = userService.Get(userId);
                return View(model);
            }
        }

        //[AllowAnonymous]
        public ActionResult UserSongCounter()
        {
            ViewBag.TotalCount = songService.GetSongsByUsername(CurrentUser.Id).Count();
            return View();
        }

        [Authorize]
        [HttpGet]
        public ActionResult MyFriendsList(int? pageNumber, string keyword)
        {
            int totalItems = 0;
            if (pageNumber == null || pageNumber == 0) pageNumber = 1;
            if (string.IsNullOrEmpty(keyword)) keyword = string.Empty;
            //var friendList = new RelationshipRepository().GetFriends(_IRepository.FindUserById(User.Identity.Name).UserId, out totalItems, keyword, pageNumber.Value);
            var friendList = songService.GetFriends(CurrentUser.Id, out totalItems, keyword, pageNumber.Value);
            ViewBag.Keyword = keyword;
            return View(new ModelForList<Relationship>()
                {
                    ListItem = friendList,
                    PagingControl = new PagingHelper()
                    {
                        CurrentPageNumber = pageNumber.Value
                    },
                    TotalSong = totalItems
                });
        }

        //[AllowAnonymous]
        [HttpGet]
        public ActionResult EditProfiles()
        {
            User model = userService.Get(CurrentUser.Id);
            EditUserModel modeledit = new EditUserModel();
            modeledit.Username = model.Username;
            modeledit.Email = model.Email;
            try { modeledit.DateOfBirth = DateTime.ParseExact(((DateTime)model.DOB).ToShortDateString(), "MM/dd/yyyy", new CultureInfo("en-US")); }
            catch
            {
                modeledit.DateOfBirth = (DateTime)model.DOB;
            }
            modeledit.Password = model.Password;
            modeledit.ConfirmPassword = model.Password;
            modeledit.Descriptions = model.AboutMe;
            modeledit.Fullname = model.DisplayName;
            modeledit.UserStatus = model.Status.ToString();
            return View(modeledit);
        }

        [Authorize]
        [HttpPost]
        public ActionResult EditProfiles(EditUserModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User();
                user.Username = User.Identity.Name;
                user.Email = model.Email;
                user.Password = model.Password;
                user.DOB = DateTime.ParseExact(model.DateOfBirth.ToShortDateString(), "MM/dd/yyyy", new CultureInfo("en-US"));
                user.AboutMe = model.Descriptions;
                //user.Status = model.UserStatus;
                user.DisplayName = model.Fullname;
                //if (model.ImageFile != null)
                //    user.Avatar = saveImage(model.ImageFile)? true: false;
                userService.SaveOrUpdate(user);
                ViewBag.Message = Resource.Song_SuccessfullyEvent;
                return View(model);
            }
            else
                return View(model);
        }

        private string saveImage(HttpPostedFileBase file)
        {
            string path = string.Empty;
            HelperContent helper = new HelperContent();
            path = helper.NewID() + Path.GetExtension(file.FileName);
            var str = Path.Combine(Server.MapPath("~/Content/Upload/Images"), path);
            file.SaveAs(str);
            path = Url.Content("~/Content/Upload/Images/" + path);
            return path;
        }

        [Authorize]
        [HttpGet]
        public ActionResult MyFavouriteSongs(int? pageNumber, string keyword)
        {
            //if (Request.IsAuthenticated)
            //{
            int totalSong = 0;
            if (pageNumber == null || pageNumber == 0) pageNumber = 1;
            if (keyword == null) keyword = string.Empty;
            var list = songService.GetMyFavouriteSongs(CurrentUser.Id, keyword, out totalSong, pageNumber.Value);
            ViewBag.Keyword = keyword;
            return View(
                new ModelForList<FavouriteSong>()
                {
                    ListItem = list,
                    TotalSong = totalSong,
                    PagingControl = new PagingHelper()
                    {
                        CurrentPageNumber = pageNumber.Value
                    }
                });
        }

        [HttpPost]
        public ActionResult DeleteFriend(int userId)
        {
            ResultObject result = new ResultObject();
            try
            {
                songService.DeleteFriend(CurrentUser.Id, userId);
                result.Result = true;
                result.Message = Resource.Song_SuccessfullyEvent;
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }
            return Json(result);
        }

        [HttpPost]
        public ActionResult AddFriend(int userId)
        {
            ResultObject result = new ResultObject();
            try
            {
                songService.AddFriend(CurrentUser.Id, userId);
                result.Result = true;
                result.Message = Resource.Song_SuccessfullyEvent;
            }
            catch (Exception ex)
            {
                result.Result = false;
                result.Message = ex.Message;
            }
            return Json(result);
        }

        [HttpGet]
        public ActionResult ChangePassword()
        {
            EditUserModel modeledit = new EditUserModel();
            modeledit.Password = string.Empty;
            modeledit.ConfirmPassword = string.Empty;
            modeledit.Email = Resource.Song_VirtualEmailData;
            return View(modeledit);
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(EditUserModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.ConfirmPassword != model.Password)
                {
                    ViewBag.Message = "Pass and confirm pass must be same.";
                }
                else
                {
                    User user = new User();
                    user.Password = "";// CommonData.MD5(model.ConfirmPassword.Trim()); ;
                    user.Username = User.Identity.Name;
                    userService.SaveOrUpdate(user);
                    ViewBag.Message = Resource.Song_SuccessfullyEvent;
                }
                return View("ChangePassword");
            }
            else
                return View(model);
        }
    }
}
